use crate::common::base_file::BaseFile;
use std::fs;
use std::fs::File;
use crate::base::BASE_FILE;
use crate::server::aes_server;
use crate::util::panic_main::panic_;

pub fn read_file() -> BaseFile {
    let secret_base = fs::read_to_string(BASE_FILE).unwrap_or_else(
        |_| panic_(format!("no `{}` find or read err , please check your workspace", BASE_FILE))
    );
    let base_json = aes_server::decrypt(&secret_base).unwrap_or_else(
        |_| panic_(format!("bad code from `{}` , please contact the merchant", BASE_FILE))
    );
    serde_json::from_str::<BaseFile>(&base_json).unwrap()
}

pub fn write_file(base_file: &BaseFile) {
    let base_json = serde_json::to_string(base_file).unwrap();
    let secret_base = aes_server::encrypt(&base_json);
    fs::write(BASE_FILE, secret_base).unwrap_or_else(
        |_| panic_(format!("no `{}` find or write err , please check your workspace", BASE_FILE))
    );
}

pub fn init_file(base_file: &BaseFile) {
    File::create(BASE_FILE).unwrap();
    write_file(base_file);
}

#[test]
fn test_init_file() {
    init_file(&BaseFile::default());
}

#[test]
fn test_read_file() {
    let base_file = read_file();
    println!("{:?}", base_file);
}

#[test]
fn test_write_file() {
    let mut base_file = read_file();
    base_file.set_used(base_file.used() + 10);
    write_file(&base_file);
    base_file = read_file();
    println!("{:?}", base_file);
}